package com.ruoyi.pointRecord.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.CodeGeneratorUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.pointRecord.dao.IProductReturnDao;
import com.ruoyi.pointRecord.domain.PointsExchangeRecord;
import com.ruoyi.pointRecord.dto.PointsExchangeRecordDTO;
import com.ruoyi.productReturn.domain.PointsReturnRequest;
import com.ruoyi.pointRecord.mapper.PointsExchangeRecordMapper;
import com.ruoyi.productReturn.mapper.PointsReturnRequestMapper;
import com.ruoyi.pointRecord.service.IProductReturnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

@Service
public class ProductReturnServiceImpl implements IProductReturnService {

    @Autowired
    private PointsExchangeRecordMapper pointsExchangeRecordMapper;

    @Autowired
    private PointsReturnRequestMapper pointsReturnRequestMapper;

    @Autowired
    private IProductReturnDao productReturnDao;

    private static final long RETURN_TIME_LIMIT_DAYS = 7;

    /**
     * 用户申请退货（提交退货申请，等待审核）
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult returnProduct(PointsExchangeRecordDTO returnRequest) {
        Long exchangeId = returnRequest.getId();
        Long userId = returnRequest.getUserId();

        PointsExchangeRecord exchangeRecord = pointsExchangeRecordMapper.selectPointsExchangeRecordById(exchangeId);
        if (exchangeRecord == null) {
            return AjaxResult.error("兑换记录不存在");
        }

        if (!exchangeRecord.getUserId().equals(userId)) {
            return AjaxResult.error("无权限操作此订单");
        }

        String statusError = validateReturnStatus(exchangeRecord);
        if (statusError != null) {
            return AjaxResult.error(statusError);
        }

        String timeError = validateReturnTimeLimit(exchangeRecord);
        if (timeError != null) {
            return AjaxResult.error(timeError);
        }

        // 检查是否已有退货申请
        PointsReturnRequest existingRequest = pointsReturnRequestMapper.selectPointsReturnRequestById(exchangeId);
        if (existingRequest != null) {
            return AjaxResult.error("该订单已有退货申请，请勿重复提交");
        }

        // 创建退货申请记录
        PointsReturnRequest returnRequestEntity = new PointsReturnRequest();
        returnRequestEntity.setReturnCode(CodeGeneratorUtil.generateCode()); // 生成退货编码
        returnRequestEntity.setExchangeId(exchangeId);
        returnRequestEntity.setUserId(userId);
        returnRequestEntity.setReturnReason(returnRequest.getReturnReason());
        returnRequestEntity.setStatus(0L); // 0-待审核
        returnRequestEntity.setCreatedBy(SecurityUtils.getUsername());
        returnRequestEntity.setLogisticsNo(returnRequest.getLogisticsNo());
        returnRequestEntity.setLogisticsCompany(returnRequest.getLogisticsCompany());
        returnRequestEntity.setLogisticsTime(returnRequest.getLogisticsTime());

        int result = pointsReturnRequestMapper.insertPointsReturnRequest(returnRequestEntity);
        if (result <= 0) {
            return AjaxResult.error("提交退货申请失败");
        }

        return AjaxResult.success("退货申请已提交，等待管理员审核", returnRequestEntity.getReturnCode());
    }


    /**
     * 管理员批量退货（直接退货，无需审核）
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult batchReturnProduct(Long[] exchangeIds, String returnReason, Long operatorId) {
        int successCount = 0;
        int failCount = 0;
        StringBuilder errorMessages = new StringBuilder();

        for (Long exchangeId : exchangeIds) {
            try {
                PointsExchangeRecord exchangeRecord = pointsExchangeRecordMapper.selectPointsExchangeRecordById(exchangeId);
                if (exchangeRecord == null) {
                    failCount++;
                    errorMessages.append("订单").append(exchangeId).append("不存在；");
                    continue;
                }

                String statusError = validateReturnStatus(exchangeRecord);
                if (statusError != null) {
                    failCount++;
                    errorMessages.append("订单").append(exchangeId).append("：").append(statusError).append("；");
                    continue;
                }

                // 管理员直接退货（积分类型 7L）
                productReturnDao.processExchangeReversal(exchangeRecord, 5L, 7L, "管理员退货失败");
                successCount++;

            } catch (Exception e) {
                failCount++;
                errorMessages.append("订单").append(exchangeId).append("处理异常：").append(e.getMessage()).append("；");
            }
        }

        if (failCount == 0) {
            return AjaxResult.success("批量退货成功，共处理" + successCount + "个订单");
        } else {
            return AjaxResult.warn("批量退货完成，成功" + successCount + "个，失败" + failCount + "个。失败原因：" + errorMessages.toString());
        }
    }

    /**
     * 取消兑换（逻辑不变）
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult cancelExchange(PointsExchangeRecord cancelRequest) {
        Long exchangeId = cancelRequest.getId();
        Long userId = cancelRequest.getUserId();

        PointsExchangeRecord exchangeRecord = pointsExchangeRecordMapper.selectPointsExchangeRecordById(exchangeId);
        if (exchangeRecord == null) {
            return AjaxResult.error("兑换记录不存在");
        }

        if (!exchangeRecord.getUserId().equals(userId)) {
            return AjaxResult.error("无权限操作此订单");
        }

        if (!exchangeRecord.getExchangeStatus().equals(1L)) {
            return AjaxResult.error("只有待发货状态的订单才能取消");
        }

        // 使用通用方法处理，状态设为已取消 4L，积分类型为 7L
        productReturnDao.processExchangeReversal(exchangeRecord, 4L, 7L, "取消失败");

        return AjaxResult.success("取消成功", exchangeRecord.getExchangeCode());
    }

    private String validateReturnStatus(PointsExchangeRecord exchangeRecord) {
        Long status = exchangeRecord.getExchangeStatus();
        if (status == 4L) return "订单已取消，无法退货";
        if (status == 5L) return "订单已退货，请勿重复操作";
        if (status == 1L || status == 2L || status == 3L) return null;
        return "订单状态异常，无法退货";
    }

    private String validateReturnTimeLimit(PointsExchangeRecord exchangeRecord) {
        LocalDate exchangeTime = exchangeRecord.getExchangeTime();
        LocalDate now = LocalDate.now();
        long daysBetween = ChronoUnit.DAYS.between(exchangeTime, now);
        if (daysBetween > RETURN_TIME_LIMIT_DAYS) {
            return "超过退货时间限制（" + RETURN_TIME_LIMIT_DAYS + "天），无法退货";
        }
        return null;
    }
}